<?php

namespace App\Http\Common\amqp\mode;

use App\Http\Common\amqp\RabbitMQ;
use PhpAmqpLib\Message\AMQPMessage;

class SimpleMode extends RabbitMQ
{
    const TYPE = __class__;

    public function sendMsg(array $msgBody): bool
    {
        // 声明队列
        $this->channel->queue_declare($this->queueName, false, true, false, false);
        $msg = new AMQPMessage($msgBody);
        $this->channel->basic_publish($msg, '', $this->queueName);
    }

    public function receiveMsg(callable $callback): void
    {
        $this->connection();
        // 声明队列
        $this->channel->queue_declare($this->queueName, false, true, false, false);
        // 消费者在接收到队列里的消息但没有返回确认结果之前,队列不会将新的消息分发给该消费者
        $this->channel->basic_qos(null, 1, null);
        // 消费消息
        $this->channel->basic_consume($this->queueName, '', false, false, false, false, $callback);
        // 等待消息调度
        $this->wait();
        // 关闭通道
        $this->channel->close();
    }
}
